import { defineStore } from 'pinia'
import {  getUserByPage, getUserProfile,getUserPermissions } from '@/api/user'
import type {  UserNotDepRes, UserProfile } from '@/types/user'
import { TOKEN } from '@/constants'
import { getItem, setItem, removeItem } from '@/utils/storage'
import adminRoutes from '@/router/modules/admin'
import { filterAdminRouter } from '@/views/Admin/config/index'
import type { TokenInfo } from '@/types/system'
import type { RouteRecordRaw } from 'vue-router'

export default defineStore('user', {
  state(): {
    token: TokenInfo | undefined
    isLoadRoute: boolean
    asyncRoutes: RouteRecordRaw[]
    userInfo: UserProfile | undefined
    userList:UserNotDepRes[]
    permissions:string[]|undefined
  } {
    return {
      token: getItem(TOKEN) || undefined,
      isLoadRoute: false,
      asyncRoutes: [],
      userInfo: undefined,
      userList:[],
      permissions:undefined
    }
  },
  actions: {
    setToken(token: TokenInfo) {
      this.token = token
      setItem(TOKEN, token)
    },
    removeToken() {
      this.token = undefined
      removeItem(TOKEN)
    },
    setPermissions(permissions: string[]) {
      this.permissions = permissions
    },
    async getPermissions() {
      await getUserPermissions()
        .then((res) => {
          this.setPermissions(res.data)
        })
        .catch(console.error)
    },
    setIsLoadRoute(status: boolean) {
      this.isLoadRoute = status
    },
    async setAsyncRoutes() {
      // 根据用户的权限列表，吧adminRoute filter一下，进行添加
      if (this.permissions === undefined||!this.permissions.length) {
        await this.getPermissions()
      }
      this.asyncRoutes = filterAdminRouter(
        this.permissions as string[],
        adminRoutes
      ) as RouteRecordRaw[]
      this.setIsLoadRoute(true)
      return this.asyncRoutes
    },
    setUserInfo(userInfo: UserProfile) {
      this.userInfo = userInfo
    },
    setUserList(userList:UserNotDepRes[]) {
      this.userList = userList
    },
    async getUserInfo() {
      await getUserProfile()
        .then((res) => {
          this.setUserInfo(res.data)
        })
        .catch(console.error)
    },
    async getUserList() {
      await getUserByPage({
        page:1,
        pageSize:9999
      })
        .then((res) => {
          this.setUserList(res.data.items)
        })
        .catch(console.error)
    },
    initUserStore() {
      this.isLoadRoute = false
      this.asyncRoutes = []
      this.userInfo = undefined
      this.userList = []
    }
  }
})
